"""
将windows10格式转化为8.3格式。

2022/04/28

Xuzehao
"""


import glob
import os
import os.path as osp
import argparse
import re

fileid = 1

parser = argparse.ArgumentParser()
parser.add_argument("--path", help="工作目录", default="deepblog_o")
parser.add_argument("--suffix", help="工作目录", default="")
parser.add_argument("--compressed", help="是否压缩文件", default="true")


def compress(content):
    # con = re.search("<style>.*</style>", content, re.DOTALL)
    # if con:
    #     con = con.group(0)
    #     content = content.replace(con, '<link rel="stylesheet" type="text/css" href="//ysuxzh.com/blog/deepblog.css">')
    # content = content.replace("<!--[if lt IE 9]>", "")
    # content = content.replace("<![endif]-->", "")
    # content = content.replace("\n", "")
    return content


def convert_(path_, indent=4):
    global fileid, suffix
    print(" " * (indent - 4), "convert for", path_)
    file2id = dict()
    for p in glob.glob(osp.join(path_, "*")):
        if osp.isfile(p):
            filename = osp.split(p)[-1]
            if filename == "index.html":
                continue
            print(" " * indent, "convert", filename)
            file2id[filename] = fileid
            with open(p, mode='r', encoding="utf8") as file:
                content = file.read()
                content = compress(content)
                with open(osp.join(path_, str(fileid) + suffix), mode='w', encoding="utf8") as fileo:
                    fileo.write(content)
            os.remove(p)
            fileid += 1
        else:
            if osp.splitext(p)[1] != ".assets":
                filename = osp.split(p)[-1]
                file2id[filename] = fileid
                flodername = fileid
                fileid += 1
                convert_(p, indent=indent+4)
                os.rename(p, osp.join(osp.split(p)[0], str(flodername)))
    if osp.isfile(osp.join(path_, "index.html")):
        print(" " * indent, "convert index.html")
        with open(osp.join(path_, "index.html"), mode="r", encoding="utf8") as file:
            content = file.read()
            for k, v in file2id.items():
                content = content.replace('<a href="%s">%s</a>' % (k, k[:-5]), '<a href="%d%s">%s</a>' % (v, suffix, k[:-5]))
                content = content.replace('src="%s"' % k, 'src="%d%s"' % (v, suffix))
                content = content.replace('<a href="%s/index.html">%s</a>' % (k, k),
                                          '<a href="%d/0%s">%s</a>' % (v, suffix, k))
            content = content.replace('<iframe src="{0}" height="99%" width="100%" style="border:0"></iframe>'\
                                      .format(suffix), '')
            content = compress(content)
            with open(osp.join(path_, "0" + suffix), mode="w", encoding="utf8") as fileo:
                fileo.write(content)
        os.remove(osp.join(path_, "index.html"))




args = parser.parse_args()
path = args.path
suffix = args.suffix
convert_(path)
